package com.example.security;


import com.example.common.JwtProperties;
import com.example.common.JwtTokenUtil;
import com.example.common.support.AjaxResponse;
import com.example.common.support.CustomException;
import com.example.common.support.CustomExceptionType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * jwt认证过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    UserDetailsService userDetailsService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CustomSecurityProperties customSecurityProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException, CustomException {

        //不需要拦截的请求路径
        final String[] ignoring = customSecurityProperties.getIgnoring();
        //当前请求路径
        final String requestURI = request.getServletPath();
        boolean not_matched = false;
        for (String ignoreUrl : ignoring) {
            not_matched = antPathMatcher.match(ignoreUrl, requestURI);
            if (not_matched) {
                break;
            }
        }


        if (!not_matched) {
            try {
                //支持从header和request.getParameter中获取token
                String jwtToken = request.getHeader(jwtProperties.getHeader());
                if (!StringUtils.hasText(jwtToken)) {
                    jwtToken = request.getParameter("token");
                }

                if (StringUtils.hasText(jwtToken)) {
                    //去掉前缀
                    if (jwtToken.startsWith("Bearer ")) {
                        jwtToken = jwtToken.substring(7);
                    }

                    String username = jwtTokenUtil.getUsernameFromToken(jwtToken);

                    //如果可以正确的从JWT中提取用户信息，并且该用户未被授权
                    if (username != null &&
                            SecurityContextHolder.getContext().getAuthentication() == null) {
                        //token有效才会创建UsernamePasswordAuthenticationToken，否则就是匿名用户
                        if (!jwtTokenUtil.isTokenExpired(jwtToken)) {
                            if (jwtTokenUtil.validateToken(jwtToken, username)) {

                                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                                //给使用该JWT令牌的用户进行授权
                                UsernamePasswordAuthenticationToken authenticationToken
                                        = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                                //此处不进行认证，直接交给spring security管理,在之后的过滤器中不会再被拦截进行二次授权了
                                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

                            }
                        } else {
                            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR
                                    , "token已经过期");
                        }
                    }
                }
                filterChain.doFilter(request, response);
            } catch (CustomException e) {
                AjaxResponse ajaxResponse = AjaxResponse.error(e);
                //response.setStatus(403);
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("UTF-8");
                try (PrintWriter writer = response.getWriter()) {
                    writer.write(objectMapper.writeValueAsString(ajaxResponse));
                }
            }
        } else {
            filterChain.doFilter(request, response);
        }

    }

}
